<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: ContentController.php 197 2011-02-18 12:45:33Z beimuaihui $
 */



class Multilang_ContentController extends Baogg_Controller_Action {

	function init() {	
		$this->initView ();
		$this->view->baseUrl = $this->_request->getBaseUrl ();
		Zend_Loader::loadClass ( 'Content' );
		$this->content = new Content ( );
		Zend_Loader::loadClass ( 'Language' );
		$this->language = new Language ( );		
	}

	/**
	 * The default action - show the home page
	 */
	public function indexAction() {

		//date grid
		$dataConfig [ 'multilang_content_id' ] 	= "#multilang_content_id";
		$dataConfig [ $multiLang->content_variable_name ]	="variable_name:10";
		$dataConfig [ $multiLang->content_content ] = "content:15";
		$dataConfig [ $multiLang->content_module_name ]	="permission_name:10";
		$dataConfig [ $multiLang->content_content_type ]	="content_type:10";
		$dataConfig [ $multiLang->g_created_time ]	="created_time:10";
		$dataConfig [ $multiLang->g_updated_time ]	="updated_time:10";
		$dataConfig [ $multiLang->g_operate ]	= "action:10@sortable:false";

		Loader::loadClass("ext::grid");
		$grid = new extGrid("data","edit","delete",array('multilang_content_id'),$dataConfig);

	//$grid->registerButton($multiLang->g_add,"showDialog(' - {$multiLang->g_add}','{$config['web']['baseurl']}multilang/content/add');",'','','add-icon');
	//$grid->registerButton($multiLang->g_import,"showDialog(' - {$multiLang->g_import}','{$config['web']['baseurl']}multilang/content/file');",'','','import-icon');
	//$grid->registerButton($multiLang->g_export,$grid->getPassParam("{$grid->id}_grid","{$config['web']['baseurl']}multilang/content/export",2),'','','export-icon');

		//key word search inputfield
		$sessionKeyword=$_SESSION["s_admin_{$session_prefix}_language_key"];
		$grid->registerTextBox($multiLang->g_keyword ,'<input type="text" name="keyword" value="'.$sessionKeyword.'" id="keyword" class="grid_search"  onkeypress="searchEvent(ext_store,this.value,event,'.$grid->_limit.')" class="grid_search" >');

		// get module list
		$multilang_module_id = $_SESSION["s_admin_{$session_prefix}_multilang_module_id"] ;
		//$module_data=$this->dataLang->getDataLang( "a.module_permission_type=1", "");
		$module_data=$this->dataLang->getDataLang( " (a.module_permission_type=0 or a.module_permission_type=1) and a.state=1", array("a.module_permission_pid asc","a.ordering desc")); 
		$module_arr['all']=$multiLang->g_all;
		$module_arr+=(array)$this->dataLang->getSelects($module_data);
		$module_selects = makeSelectList('module_permission_id_post', $module_arr, '', ' class="grid_select"  onchange="searchComboEvent(ext_store,this.value,\'module_id\',0,'.$grid->_limit.');" class="grid_select" ', $multilang_module_id);

		$grid->registerTextBox($multiLang->content_module,$module_selects);
		$grid->gridHeight = 400;


		$this->view->grid = $grid;
	}


	/*
	 * data list
	 */
	function dataAction() {
		$list = $this->content->getList();
		echoJsonData ( $list["rs"], $list["total"] );
		$this->_helper->viewRenderer->setNoRender ();
	}

	/*
	 *  add page
	 */
	function addAction() {
		global $config,$multiLang;
		$this->view->postaction="add";

		//$module_data=$this->dataLang->getDataLang( "a.module_permission_type=1", "");
		$module_data=$this->dataLang->getDataLang( " (a.module_permission_type=0 or a.module_permission_type=1) and a.state=1", array("a.module_permission_pid asc","a.ordering desc")); 
		// $module_data=$this->dataLang->getDataLang( " a.module_permission_type=1 and a.state=1", array("a.module_permission_pid asc","a.ordering desc")); 
		$module_arr=$this->dataLang->getSelects($module_data);
		$this->view->module_selects = makeSelectList('module_permission_id_post', $module_arr, '', ' class="grid_select""', $multilang_module_id);
		$this->view->contenttype_selects = makeSelectList('content_type[]', $config['global']['g_multilang_contenttype'], '', ' class="grid_select""', 1);

		//toolbar
		Loader::loadClass('ext::toolbar');
		$this->view->toolbarButton = new extToolBar();
		$this->view->toolbarButton->registerButton ( $multiLang->g_save, "handleForm('adminForm',\"{$config['web']['baseurl']}multilang/content/save\")", 'save-icon' );
		$this->view->toolbarButton->registerButton ( $multiLang->g_cancel, 'parent.dialog.hide()', 'cancel-icon' );
	}

	/*
	 *  edit page
	 */
	function editAction() {
		global $config,$multiLang;
		$session_prefix = getPageName();
		$this->view->postaction="edit";

		$module_data=$this->dataLang->getDataLang( " (a.module_permission_type=0 or a.module_permission_type=1) and a.state=1", array("a.module_permission_pid asc","a.ordering desc")); 
		//$module_data=$this->dataLang->getDataLang( " a.module_permission_type=1 and a.state=1", array("a.module_permission_pid asc","a.ordering desc"));
		$module_arr=$this->dataLang->getSelects($module_data);
		$this->view->module_selects = makeSelectList('module_permission_id_post', $module_arr, '', ' class="grid_select""', $multilang_module_id);

		//$content_ids=implode(',',$_POST['cid']);
		if (is_array($_GET['multilang_content_id'])) {
			//print_r ($_GET['multilang_content_id']);
			$content_ids=implode(',',$_GET['multilang_content_id']);
			$condition = " and multilang_content.multilang_content_id in ({$content_ids})";
		}elseif((int)$_GET['multilang_content_id'] != '') {
				$condition = " and  multilang_content.multilang_content_id='".$_GET['multilang_content_id']."'";
		}

		$orderby=$_SESSION[$session_prefix."_orderby"];
		$orderby_desc=$_SESSION[$session_prefix."_orderby_desc"];

		$this->view->contentData=$this->content->getById($_GET["multilang_content_id"]);

		//toolbar
		Loader::loadClass('ext::toolbar');
		$this->view->toolbarButton = new extToolBar();
		$this->view->toolbarButton->registerButton ( $multiLang->g_save, "handleForm('adminForm',\"{$config['web']['baseurl']}multilang/content/save\")", 'save-icon' );
		$this->view->toolbarButton->registerButton ( $multiLang->g_cancel, 'parent.dialog.hide()', 'cancel-icon' );
	}

	/*
	 *  delete action
	 */
	function deleteAction() {
		global $db,$config,$multiLang;
		foreach((array)$_GET['multilang_content_id'] as $id)
		{
			if (strlen($id)>0)
			{
				$content=$this->content->getOne($id);
				$idArr[$id]=$content[0]["variable_name"];

				if ($this->content->delete($id))
					$succResult[]=$content[0]["variable_name"];
				else
					$failResult[]=$content[0]["variable_name"];
			}

		}

		if(is_array($failResult)){
			$fail_str=implode(", ",$failResult);
			$msg .="<br >".$multiLang->g_delete_fail." <br >".$fail_str."<br >";
			$message = "False to delete content,"." <br >".$fail_str."<br >";
			$flag=0;
		}else{
			$msg .=$multiLang->g_delete_ok." <br >";
			$flag=1;
			$fn="ext_store.reload();";
			$message = "Delete content successful";
		}

		echo actionMsg($flag, $msg, $fn);
		$this->_helper->viewRenderer->setNoRender ();
		$log=array();
		$log['module_permission_id'] 	= getPermissionId();
		$log['users_id']				= $_SESSION['s_admin_user_id'];
		$log['message']					= $message;
		$log['log_sql']					= debugDb();
		$log['result']					= $flag;
		$log['log_users_id']			= $_SESSION['s_admin_user_id'];
		//print_r($log);
		insertLog($log);
	}

	/*
	 *  add or edit  to db action
	 */
	function saveAction() {
		global $db,$config,$multiLang;

		$tmp1 = array();
		$tmp2 = array();

		if ($_POST['postaction'] == 'edit')
		{
			// Edit Content

			$post_permission=array_unique((array)$_POST["module_permission_id_hidden"]);
			// foreach contents
			foreach ((array)$_POST['content_id'] as $k=>$v)
			{
				$_POST['variable_name'][$k]=trim($_POST['variable_name'][$k]);
				$module_permission_id_hidden=$_POST['module_permission_id_hidden'][$k];


				/*if(strstr($_POST['variable_name'][$k]," ")){
					$failResult[]=$_POST['variable_name'][$k];
					continue;
				}*/

				//check varable name is valid?
				$regex='/^[a-zA-Z][a-zA-Z0-9_]{0,256}$/';
				preg_match_all($regex,$_POST['variable_name'][$k],$regex_group,PREG_PATTERN_ORDER);
				if (count($regex_group[0])<1){
					$failResult[]=$_POST['variable_name'][$k];
					continue;
				}

				// Check if variable name exists
				$checkSql = "select count(*)  as total from multilang_content
					where multilang_content_id={$_POST['content_id'][$k]}
					and (`module_permission_id` = '{$module_permission_id_hidden}' or `module_permission_id`='000000'); ";

				$stmt='';     $stmt=$db->query($checkSql);
				$check=$stmt->fetchAll();

				if ($check[0]["total"]){
						$checkSql2 = "select count(*)  as total from multilang_content where multilang_content_id!={$_POST['content_id'][$k]} and variable_name='{$_POST['variable_name'][$k]}'  and (`module_permission_id` = '{$module_permission_id_hidden}' or `module_permission_id`='000000'); ";
						$stmt='';     $stmt=$db->query($checkSql2);
						$check2=$stmt->fetchAll();

						if ($check2[0]["total"]){
								$failResult[]= $_POST['variable_name'][$k];
						}else{

							$sql= "update multilang_content set variable_name= '{$_POST['variable_name'][$k]}',
								content_type={$_POST['content_type'][$k]},
								description='{$_POST['description'][$k]}' where  multilang_content_id={$_POST['content_id'][$k]} ;";
							//echo $sql;  updated_time='".date('Y-m-d H:i:s')."',"."

							$log_sql.=$sql;
							$rs=$db->query($sql);
							$content = trim($_POST['content'][$k]);
							$sql= "update multilang_translate set content= '{$content}',
									updated_time='".date('Y-m-d H:i:s')."'
									where  multilang_content_id={$_POST['content_id'][$k]} and language_id=1 ;";

							//echo $sql;
							$log_sql.=$sql;
							$rs=$db->query($sql);
							if ($rs){
								$succResult[]=$_POST['variable_name'][$k];
							}else{
								$failResult[]=$_POST['variable_name'][$k];
							}
						}
				}else{

					$failResult[]= $_POST['variable_name'][$k];

				}
			}

		}else{
			// New content
			$module_permission_id_post=$_POST["module_permission_id_post"];
			$sql_1="INSERT INTO `multilang_content`(`module_permission_id`,`variable_name`,`content_type`,`description`,`updated_by`,`updated_time`) 	VALUES " ;
			$sql_2="INSERT INTO `multilang_translate` (`multilang_content_id`,`language_id`,`content`,`updated_by`,`updated_time`) VALUES ";
			$session_user_id=$_SESSION['s_admin_user_id'] ;
			foreach ((array)$_POST['variable_name'] as $k=>$v)
			{
				//foreasy inputs

				$session_user_id=1;
				if ($v && $session_user_id )
				{

					$_POST['variable_name'][$k]=trim($_POST['variable_name'][$k]);

					//check varable name is valid?
					$regex='/^[a-zA-Z][a-zA-Z0-9_]{0,256}$/';
					preg_match_all($regex,$_POST['variable_name'][$k],$regex_group,PREG_PATTERN_ORDER);
					if (count($regex_group[0])<1){
						$failResult[]=$_POST['variable_name'][$k];
						continue;
					}
					// Check if variable name exists
					$checkSql = "select count(*)  as total from `multilang_content` where `variable_name` = '".trim($v)."' and (`module_permission_id` = '{$module_permission_id_post}' or `module_permission_id`='000000' ); ";

					$stmt='';     $stmt=$db->query($checkSql);
					$check=$stmt->fetchAll();

					if ($check[0]["total"])	{
						//if variable name exist
						$failResult[] = $v;
					}else{
						$sql= $sql_1."('{$module_permission_id_post}','{$v}', {$_POST['content_type'][$k]}, '{$_POST['description'][$k]}', '{$session_user_id}','".date('Y-m-d H:i:s')."');";

						$log_sql.=$sql;
						$rs=$db->query($sql);
						//$insert_id = mysql_insert_id();
						$insert_id=$db->lastInsertId();
						$content = $_POST['content'][$k];
						$sql = $sql_2."({$insert_id},1,'{$_POST['content'][$k]}','{$session_user_id}','".date('Y-m-d H:i:s')."');";
						$log_sql.=$sql;
						$rs=$db->query($sql);
						if ($rs){
							$succResult[]=$_POST['variable_name'][$k];
						}else{
							$failResult[]=$_POST['variable_name'][$k];
						}
					}
				}
			}

		}

		//echo $log_sql;
		//gen language php files
		$this->language->genLangFiles();

		if(is_array($failResult)){
			array_unique($failResult);
			$fail_str=implode(", ",$failResult);
			$msg .=$multiLang->g_save_fail."<br >".$fail_str;
			$flag=0;
			$message="Fail to save content .";
		}else{
			$msg .=$multiLang->g_save_ok."<br >";
			$flag=1;
			$message="Succ to save content.";
		}

		echo actionMsg($flag, $msg, $fn);
		$this->_helper->viewRenderer->setNoRender ();

		$log=array();
		$log['module_permission_id'] 	= getPermissionId();
		$log['users_id']				= $_SESSION['s_admin_user_id'];
		$log['message']					= $message;
		$log['log_sql']					= $log_sql;
		$log['result']					= $flag;
		$log['log_users_id']			= $_SESSION['s_admin_user_id'];
		//print_r($log);
		insertLog($log);
	}

	/**
	 *  export content to download
	 */
	function exportAction(){
		global $db,$config;
		checkLogin($_SESSION['s_admin_user_id']);
		checkPermission($_SESSION['s_admin_role_id']);
		header('Content-Type: application/octet-stream; charset=iso-8859-1');
		header("Accept-Ranges: bytes");
		header("Content-Disposition: attachment; filename=\"language_" . date('YmdHis') . ".csv\"");
		if (is_array($_GET['multilang_content_id'])) {
			$content_ids=implode(',',$_GET['multilang_content_id']);
			$condition = " and c.multilang_content_id in ({$content_ids})";
			$flag=TRUE;
		}elseif((int)$_GET['multilang_content_id'] != '') {
			$condition = " and  c.multilang_content_id='".$_GET['multilang_content_id']."'";
			$flag=TRUE;
		}else{
			$flag=FALSE;
		}

		if($flag){
			$sql = "select c.multilang_content_id,c.module_permission_id,c.variable_name,
				c.content_type,c.description,t.language_id,t.content,l.language_code
				from multilang_content as c, multilang_translate as t, language l
				where  c.multilang_content_id=t.multilang_content_id
				and t.language_id = l.language_id
				{$condition}
				order by c.multilang_content_id,t.language_id asc
			;";

			$stmt='';     $stmt=$db->query($sql);
			$contentData = $stmt->fetchAll();
			foreach ((array)$contentData as $k=>$v) {
				echo implode("____",$v)."\n-newline-";
			}

			//print_r($contentData);
		}else{
			echo "Nothing";
		}

		$this->_helper->viewRenderer->setNoRender ();
	}

	/**
	 *  update file page
	 */
	function fileAction(){
		global  $multiLang;
		checkLogin($_SESSION['s_admin_user_id']);
		checkPermission($_SESSION['s_admin_role_id']);
		//toolbar
		Loader::loadClass('ext::toolbar');
		$this->view->toolbarButton = new extToolBar();
		$this->view->toolbarButton->registerButton ( $multiLang->g_import, "submitForm()", 'import-icon' );
		$this->view->toolbarButton->registerButton ( $multiLang->g_cancel, 'parent.dialog.hide()', 'cancel-icon' );
	}

	/**
	 * upload file and parse file's content
	 */
	function importAction(){
		global $db,$config,$multiLang;
		checkLogin($_SESSION['s_admin_user_id']);
		checkPermission($_SESSION['s_admin_role_id']);
		//custom view
		$this->_helper->viewRenderer->setNoRender();
		Zend_Loader::loadClass('Zend_View');
		$view = new Zend_View();
		$view->setScriptPath($config['system']['root']."application/Multilang/views/scripts/content");
		$view->dataLang=$this->dataLang;

		if($_FILES['upfile']){
			$import_type=$_POST["import_type"];
			$uploadDir			= '../files/tmp';
			//add new dir
			if(!is_dir($uploadDir))	{
				mkdir($uploadDir,0777);
				@chmod($thumbnailDir,0777);
			}

			$uploadFileName		= $_FILES['upfile']['name'];
			$uploadFileType		= $_FILES['upfile']['type'];
			$uploadFileTmpName	= $_FILES['upfile']['tmp_name'];


			$newfilename=md5(microtime()).".txt";
			$fullfilename=$uploadDir."/".$newfilename;
			if (move_uploaded_file( $_FILES['upfile']['tmp_name'],$fullfilename)){
				// file upload success

				if($import_type=="php"){
					//import from php
					$file_content=file_get_contents($fullfilename);
					//echo $file_content."<br />";
					//echo preg_match_all('/\s\$(?<name>[a-zA-Z].*)\=(?<value>.*)\;/',$file_content,$regex_group,PREG_PATTERN_ORDER);
					preg_match_all('/\s*\$([a-zA-Z].*?)\s*\=\s*(.*)\s*\;/',$file_content,$regex_group,PREG_PATTERN_ORDER);
					//exit;

					//Get language List
					$lang_list = $this->language->getAllByState();
					foreach ((array)$lang_list as $key => $value) {
						$lang_arr[$lang_list[$key]['language_id']]=$lang_list[$key]['language_name'];
					}
					//$lang_selects = makeSelectList('language_id', $lang_arr, '', ' id="language_id" onChange="changeLanguage(this.value)" ', $translate_lang_id);
					$view->lang_selects = makeSelectList('language_id', $lang_arr, '',
						'class="grid_select" onchange="searchComboEvent(ext_store,this.value,\'language_id\');" class="grid_select"', 1);

					//Get Module List
					$module_data=$this->dataLang->getDataLang( " (a.module_permission_type=0 or a.module_permission_type=1) and a.state=1", array("a.module_permission_pid asc","a.ordering desc")); 
					//$module_data=$this->dataLang->getDataLang( "a.module_permission_type=1", "");
					$module_arr=$this->dataLang->getSelects($module_data);
					$view->module_selects = makeSelectList('module_permission_id_post', $module_arr, '',
						' class="grid_select"  onchange="searchComboEvent(ext_store,this.value,\'module_permission_id\',0);" class="grid_select" ', $multilang_module_id);

					$view->variable_names=($regex_group[1]);
					$view->variable_values=($regex_group[2]);

					//toolbar
					Loader::loadClass('ext::toolbar');
					$view->toolbarButton = new extToolBar();
					$view->toolbarButton->registerButton (  $multiLang->g_save , "handleForm('adminForm',\"{$config['web']['baseurl']}multilang/content/savephp\")", 'save-icon' );
					$view->toolbarButton->registerButton ( $multiLang->g_cancel, 'parent.dialog.hide()', 'cancel-icon' );
					echo $view->render('importphp.phtml');


				}else{
					//import from csv
					$file_content=file_get_contents($fullfilename);
					//echo $file_content."<br />";
					//echo preg_match_all('/\s\$(?<name>[a-zA-Z].*)\=(?<value>.*)\;/',$file_content,$regex_group,PREG_PATTERN_ORDER);
					//preg_match_all('/\s\$([a-zA-Z].*)\=(.*)\;/',$file_content,$regex_group,PREG_PATTERN_ORDER);
					//exit;
					$lines = preg_split("/\n-newline-/",$file_content);
					$contents=array();
					foreach ($lines as $line) {
						if (strlen($line)>10)
							$contents[]=explode("____",$line);
					}
					$view->contents=$contents;

					//toolbar
					Loader::loadClass('ext::toolbar');
					$view->toolbarButton = new extToolBar();
					$view->toolbarButton->registerButton ( $multiLang->g_save, "handleForm('adminForm',\"{$config['web']['baseurl']}multilang/content/savecsv\")", 'save-icon' );
					$view->toolbarButton->registerButton ( $multiLang->g_cancel, 'parent.dialog.hide()', 'cancel-icon' );
					echo $view->render('importcsv.phtml');
				}
			}
		}
	}


	/**
	 *	save from csv's content to db
	 */
	function savecsvAction(){
		global $db,$config,$multiLang;
		checkLogin($_SESSION['s_admin_user_id'],1);
		checkPermission($_SESSION['s_admin_role_id'],1);

		$flag=2;
		$session_user_id=1;
		$tmp1 = array();
		$tmp2 = array();
		$language_id=1;

		$sql_1="INSERT INTO `multilang_content`(`module_permission_id`,`variable_name`,`content_type`,`description`,`updated_by`,`updated_time`) 	VALUES " ;
		$sql_2="INSERT INTO `multilang_translate` (`multilang_content_id`,`language_id`,`content`,`updated_by`,`updated_time`) VALUES ";


		foreach ((array)$_POST['variable_name'] as $k=>$v)
		{
			//for each variable name

			$v=trim($v);
			$content=$_POST['content'][$k];
			$content=$content[1];
			$variable_name=trim($_POST['variable_name'][$k]);
			$enable_check=$_POST['enable_check'][$k];
			$update_check=$_POST['update_check'][$k];
			$module_permission_id_post=$_POST['module_permission_id_post'][$k];

			if ($v && $session_user_id && $enable_check)
			{
				//login and enable
				$regex='/^[a-zA-Z][a-zA-Z0-9_]{0,256}$/';
				preg_match_all($regex,$variable_name,$regex_group,PREG_PATTERN_ORDER);
				if (count($regex_group[0])<1){
					$failResult[]=$variable_name;
					continue;
				}

				// Check if variable name exists
				$checkSql = "select count(*)  as total
								from `multilang_content`
								where `variable_name` = '".$v."'
								and (`module_permission_id` = '{$module_permission_id_post}'
									or `module_permission_id`='000000' ); ";

				$stmt='';     $stmt=$db->query($checkSql);
				$check=$stmt->fetchAll();
				//echo $checkSql;

				if ($check[0]["total"])	{
					//variable is exist
					$sql = "select multilang_content_id  from `multilang_content` where `variable_name` = '".$v."' and (`module_permission_id` = '{$module_permission_id_post}' ); ";
					$stmt='';     $stmt=$db->query($sql);
					$rs=$stmt->fetchAll();
					$insert_id=$rs[0]["multilang_content_id"];
					$sql = "select  count(*)  as total
								from multilang_translate
								where multilang_content_id = '{$insert_id}'
								and  language_id = '{$language_id}' ; ";
					$stmt='';     $stmt=$db->query($sql);
					$rs=$stmt->fetchAll();
					if ($rs[0]["total"]>0){
						if($update_check){
							$update_sql="update multilang_content
											set  content_type={$_POST['content_type'][$k]},
											description='{$_POST['description'][$k]}',
											updated_by='{$session_user_id}',
											updated_time='".date('Y-m-d H:i:s')."'
											where  multilang_content_id={$insert_id}
											;";
							//echo $update_sql;
							$rs_content=$db->query($update_sql);

							$tran_sql="update multilang_translate
											set  content='{$content}',
											updated_by='{$session_user_id}',
											updated_time='".date('Y-m-d H:i:s')."'
											where  multilang_content_id={$insert_id}
											and language_id={$language_id}
											;";
							$rs_tran=$db->query($tran_sql);
							if($rs_content && $rs_tran){
								$succResult[]=$variable_name;
							}else{
								$failResult[] = $variable_name;
							}
						}
					}else{
						if ($language_id<>1){
							$sql = "select  count(*)  as total
								from  multilang_content c,multilang_translate t
								where c.multilang_content_id=t.multilang_content_id
								and c.variable_name = '{$v}'
								and  language_id = 1 ; ";
							$stmt='';     $stmt=$db->query($sql);
							$rs=$stmt->fetchAll();
							if ($rs[0]["total"]>0){

								$sql = $sql_2."({$insert_id},{$language_id},'{$content}','{$session_user_id}','".date('Y-m-d H:i:s')."');";
								$log_sql.=$sql;
								$rs=$db->query($sql);
								if ($rs){
									$succResult[]=$variable_name;
								}else{
									$failResult[]=$variable_name;
								}
							}else{
								$failResult[] = $variable_name;
							}
						}else{
								$sql = $sql_2."({$insert_id},{$language_id},'{$content}','{$session_user_id}','".date('Y-m-d H:i:s')."');";
								$log_sql.=$sql;
								$rs=$db->query($sql);
								if ($rs){
									$succResult[]=$variable_name;
								}else{
									$failResult[]=$variable_name;
								}
						}
					}


				}else{

					$sql= $sql_1."('{$module_permission_id_post}','{$v}', {$_POST['content_type'][$k]}, '{$_POST['description'][$k]}', '{$session_user_id}','".date('Y-m-d H:i:s')."');";
					$log_sql.=$sql;
					$rs=$db->query($sql);
					$insert_id = $db->lastInsertId();

					if ($language_id<>1){
						$sql = "select  count(*)  as total
							from  multilang_content c,multilang_translate t
							where c.multilang_content_id=t.multilang_content_id
							and c.variable_name = '{$v}'
							and  language_id = 1 ; ";

						$stmt='';     $stmt=$db->query($sql);
						$rs=$stmt->fetchAll();
						if ($rs[0]["total"]>0){
							$sql = $sql_2."({$insert_id},{$language_id},'{$content}','{$session_user_id}','".date('Y-m-d H:i:s')."');";
							$log_sql.=$sql;
							$rs=$db->query($sql);
							if ($rs){
								$succResult[]=$variable_name;
							}else{
								$failResult[]=$variable_name;
							}
						}else{
							$failResult[] = $variable_name;
						}
					}else{
							$sql = $sql_2."({$insert_id},{$language_id},'{$content}','{$session_user_id}','".date('Y-m-d H:i:s')."');";

							$log_sql.=$sql;

							$rs=$db->query($sql);

							if ($rs){
								$succResult[]=$variable_name;
							}else{
								$failResult[]=$variable_name;
							}
					}

				}
			}

		}

		//gen language php files
		$this->language->genLangFiles();

		if(is_array($failResult)){
			array_unique($failResult);
			$fail_str=implode(", ",$failResult);
			$msg .=$multiLang->g_save_fail."<br >".$fail_str;
			$flag=0;
			$message="Fail to save csv.";
		}else{
			$msg .=$multiLang->g_save_ok." <br >";
			$flag=1;
			$message="Succ to save csv .";

		}

		if ($flag==2) {
			$flag=0;
			$msg=$multiLang->g_save_fail."fail2".$msg;
		}
		echo actionMsg($flag, $msg, $fn);
		$this->_helper->viewRenderer->setNoRender();

		$log=array();
		$log['module_permission_id'] 	= getPermissionId();
		$log['users_id']				= $_SESSION['s_admin_user_id'];
		$log['message']					= $message;
		$log['log_sql']					= $log_sql;
		$log['result']					= $flag;
		$log['log_users_id']			= $_SESSION['s_admin_user_id'];
		//print_r($log);
		insertLog($log);
	}

	/**
	 *	save from php's content to db
	 */
	function savephpAction(){
		global $db,$config,$multiLang;
		checkLogin($_SESSION['s_admin_user_id'],1);
		checkPermission($_SESSION['s_admin_role_id'],1);

		$flag=2;

		$language_id=$_POST['language_id'];
		$module_permission_id_post=$_POST['module_permission_id_post'];


		if ((strlen($language_id)>0) &&(strlen($module_permission_id_post)>0)  )
		{

			$tmp1 = array();
			$tmp2 = array();


			$sql_1="INSERT INTO `multilang_content`(`module_permission_id`,`variable_name`,`content_type`,`description`,`updated_by`,`updated_time`) 	VALUES " ;
			$sql_2="INSERT INTO `multilang_translate` (`multilang_content_id`,`language_id`,`content`,`updated_by`,`updated_time`) VALUES ";
			$session_user_id=1;
			foreach ((array)$_POST['variable_name'] as $k=>$v)
			{
				$v=trim($v);
				$content=str_replace("'",'"' ,$_POST['content'][$k]);
				$variable_name=trim($v);
				$variable_check=$_POST['variable_check'][$k];
				$variable_update=$_POST['variable_update'][$k];

				if ($v && $session_user_id && $variable_check)
				{

					$regex='/^[a-zA-Z][a-zA-Z0-9_]{0,256}$/';
					preg_match_all($regex,$variable_name,$regex_group,PREG_PATTERN_ORDER);
					if (count($regex_group[0])<1){
						$failResult[]=$variable_name;
						continue;
					}

					// Check if variable name exists
					$checkSql = "select count(*)  as total
									from `multilang_content`
									where `variable_name` = '".$v."'
									and (`module_permission_id` = '{$module_permission_id_post}'
										or `module_permission_id`='000000' ); ";

					$stmt='';     $stmt=$db->query($checkSql);
					$check=$stmt->fetchAll();
					//echo $checkSql;

					if ($check[0]["total"])	{
						$sql = "select multilang_content_id  from `multilang_content` where `variable_name` = '".$v."' and (`module_permission_id` = '{$module_permission_id_post}' ); ";

						$stmt='';     $stmt=$db->query($sql);
						$rs=$stmt->fetchAll();



						$insert_id=$rs[0]["multilang_content_id"];
						$sql = "select  count(*)  as total
									from multilang_translate
									where multilang_content_id = '{$insert_id}'
									and  language_id = '{$language_id}' ; ";


						$stmt='';     $stmt=$db->query($sql);
						$rs=$stmt->fetchAll();
						if ($rs[0]["total"]>0){
							if($variable_update){
								$update_sql="update multilang_content
												set  content_type={$_POST['content_type'][$k]},
												description='{$_POST['description'][$k]}',
												updated_by='{$session_user_id}',
												updated_time='".date('Y-m-d H:i:s')."'
												where  multilang_content_id={$insert_id}
												;";
								//echo $update_sql;


								$rs_content=$db->query($update_sql);

								$tran_sql="update multilang_translate
												set  content='{$content}',
												updated_by='{$session_user_id}',
												updated_time='".date('Y-m-d H:i:s')."'
												where  multilang_content_id={$insert_id}
												and language_id={$language_id}
												;";


								$rs_tran=$db->query($tran_sql);
								if($rs_content && $rs_tran){
									$succResult[]=$variable_name;
								}else{
									$failResult[] = $variable_name;
								}
							}
						}else{
							if ($language_id<>1){
								$sql = "select  count(*)  as total
									from  multilang_content c,multilang_translate t
									where c.multilang_content_id=t.multilang_content_id
									and c.variable_name = '{$v}'
									and  language_id = 1 ; ";


								$stmt='';     $stmt=$db->query($sql);
								$rs=$stmt->fetchAll();
								if ($rs[0]["total"]>0){
									$sql = $sql_2."({$insert_id},{$language_id},'{$content}','{$session_user_id}','".date('Y-m-d H:i:s')."');";


									$log_sql.=$sql;
									$rs=$db->query($sql);
									if ($rs){
										$succResult[]=$variable_name;
									}else{
										$failResult[]=$variable_name;
									}
								}else{
									$failResult[] = $variable_name;
								}
							}else{
									$sql = $sql_2."({$insert_id},{$language_id},'{$content}','{$session_user_id}','".date('Y-m-d H:i:s')."');";


									$log_sql.=$sql;
									$rs=$db->query($sql);
									if ($rs){
										$succResult[]=$variable_name;
									}else{
										$failResult[]=$variable_name;
									}
							}
						}


					}else{
						$sql= $sql_1."('{$module_permission_id_post}','{$v}', {$_POST['content_type'][$k]}, '{$_POST['description'][$k]}', '{$session_user_id}','".date('Y-m-d H:i:s')."');";


						$log_sql.=$sql;
						$rs=$db->query($sql);
						$insert_id = $db->lastInsertId();

						if ($language_id<>1){
							$sql = "select  count(*)  as total
								from  multilang_content c,multilang_translate t
								where c.multilang_content_id=t.multilang_content_id
								and c.variable_name = '{$v}'
								and  language_id = 1 ; ";
							//echo $sql;

							$rs=$db->query($sql);
							if ($rs[0]["total"]>0){
								$sql = $sql_2."({$insert_id},{$language_id},'{$content}','{$session_user_id}','".date('Y-m-d H:i:s')."');";
								$log_sql.=$sql;
								$rs=$db->query($sql);
								if ($rs){
									$succResult[]=$variable_name;
								}else{
									$failResult[]=$variable_name;
								}
							}else{
								$failResult[] = $variable_name;
							}
						}else{
								$sql = $sql_2."({$insert_id},{$language_id},'{$content}','{$session_user_id}','".date('Y-m-d H:i:s')."');";

								$log_sql.=$sql;
								$rs=$db->query($sql);

								if ($rs){
									$succResult[]=$variable_name;
								}else{
									$failResult[]=$variable_name;
								}
						}

					}
				}
			}

		}


		//gen language php files
		$this->language->genLangFiles();

		if(is_array($failResult)){
			array_unique($failResult);
			$fail_str=implode(", ",$failResult);
			$msg .=$multiLang->g_save_fail." : <br >".$fail_str;
			$flag=0;
			$message="Fail to save php.";
		}else{
			$msg .=$multiLang->g_save_ok." <br >";
			$flag=1;
			$message="Succ to save php.";	

		}

		if ($msg)
			echo actionMsg($flag, $msg, $fn);

		$this->_helper->viewRenderer->setNoRender();
		$log=array();
		$log['module_permission_id'] 	= getPermissionId();
		$log['users_id']				= $_SESSION['s_admin_user_id'];
		$log['message']					= $message;
		$log['log_sql']					= $log_sql;
		$log['result']					= $flag;
		$log['log_users_id']			= $_SESSION['s_admin_user_id'];
		//print_r($log);
				
		insertLog($log);
	}

}
